import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import PublicActivitiesView from '../views/PublicActivitiesView.vue'
import PublicActivityDetailView from '../views/PublicActivityDetailView.vue'
import ActivityManagementView from '../views/ActivityManagementView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: true }
  },
  {
    path: '/public-activities',
    name: 'public-activities',
    component: PublicActivitiesView,
    meta: { requiresAuth: true }
  },
  {
    path: '/public-activities/:id',
    name: 'public-activity-detail',
    component: PublicActivityDetailView,
    meta: { requiresAuth: true }
  },
  {
    path: '/activity-management',
    name: 'activity-management',
    component: ActivityManagementView,
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  {
    path: '*',
    redirect: '/'
  }
]

const router = new VueRouter({
  routes
})

// 全局前置路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('isAuthenticated') === 'true'
  const isAdmin = localStorage.getItem('isAdmin') === 'true'

  // 检查是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      next({ name: 'login' }) // 未登录用户重定向至登录页
    } else {
      // 检查是否需要管理员权限
      if (to.matched.some(record => record.meta.requiresAdmin) && !isAdmin) {
        alert('无权限访问该页面')
        next({ name: 'home' }) // 非管理员用户返回首页
      } else {
        next()
      }
    }
  } else {
    next()
  }
})

export default router